<template>
  <div>
    <div style="margin-bottom: 10px;">
      <el-button type="primary" size="mini" @click="handleMeterHookClick">挂表</el-button>
      <el-button v-if="needImport" type="info" size="mini" @click="handleImport">导入</el-button>
      <el-button type="danger" size="mini" @click="handleDelete">删除</el-button>
    </div>

    <div>
      <el-table :data="terminalsXbInfoList" size="mini"
                border @selection-change="handleSelectionChange" :height="getAvailableHeight">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column type="index" width="40" align="center" label="#"/>
        <el-table-column label="用户编号" align="center" prop="terminalID" width="125"/>
        <el-table-column label="用户名称" align="left" prop="userName"/>
        <el-table-column label="用户地址" align="left" prop="terminalAddress"/>
        <el-table-column label="生产厂家" align="center" prop="supplierID" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.terminal_supplier" :value="scope.row.supplierID"/>
          </template>
        </el-table-column>
        <el-table-column label="口径" align="center" prop="caliber" width="60"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="70">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['device:terminalsXbInfo:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        :total="total"
        :page-sizes="[15, 30, 45, 60]"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="loadMeterHookedData"
      />
    </div>

    <UnbindMeterSelector ref="refXbUnbindMeterSelector" :callback="loadMeterHookedData"/>


    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip"><el-checkbox v-model="upload.updateSupport"/>是否更新已经存在的用户数据</div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                    @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <importFailedTable ref="refImportFailedTable" :callback="loadMeterHookedData"/>
  </div>
</template>

<script>
import UnbindMeterSelector from './UnbindMeterSelector'
import importFailedTable from './importFailedTable'
import {getBoundTerminalsXb, batchUnbindTerminalsXbInfo} from '@/api/leakage/terminalsXbInfo'
import {getToken} from "@/utils/auth";
export default {
  name: "MeterHooking",
  dicts: ['terminal_supplier'],
  components: {
    UnbindMeterSelector,
    importFailedTable
  },
  props: {
    needImport: {
      type: Boolean,  // Prop的类型
      required: false , // 该Prop是必需的
      default: true //暂时默认true
    }
  },
  data() {
    return {
      screenHeight: null,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 户表档案表格数据
      terminalsXbInfoList: [],
      editingZoneObj: undefined,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        areaID: null
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/device/terminalsXbInfo/importData"
      },
    }
  },
  methods: {
    updateEditingZone(zone) {
      this.editingZoneObj = zone
      this.loadMeterHookedData()
    },
    loadMeterHookedData() {
      if (this.editingZoneObj) {
        this.queryParams.areaID = this.editingZoneObj.areaId
        this.queryParams.terminalMark = 1
      }
      getBoundTerminalsXb(this.queryParams).then(res => {
        this.terminalsXbInfoList = res.rows
        this.total = res.total;
        this.$forceUpdate()
      })
    },
    handleMeterHookClick() {
      this.$refs.refXbUnbindMeterSelector.openDialog(this.editingZoneObj)
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleDelete(row) {
      const IDs = row.id || this.ids.join(',');
      const params = {
        ids: IDs,
      }
      this.$modal.confirm('是否确认删除所选挂接户表？').then(function () {
        return batchUnbindTerminalsXbInfo(params);
      }).then(() => {
        this.loadMeterHookedData();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "户表导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('device/terminalsXbInfo/importTemplate', {}, `户表档案_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      let data = response.data;
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      if(data.failedXbList.length==0){
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + data.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
        this.loadMeterHookedData();
      }else{
        this.$refs.refImportFailedTable.openDialog(data)
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  },
  created() {
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - 255
    },
  },
}
</script>

<style scoped>

</style>
